package version3.part2.Client.retry;

import com.github.rholder.retry.*;
import version3.part2.Client.rpcClient.RpcClient;
import version3.part2.common.Message.RpcRequest;
import version3.part2.common.Message.RpcResponse;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class guavaRetry {

    public RpcResponse sendRequestWithRetry(RpcRequest rpcRequest,RpcClient rpcClient) {
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfException()
                .retryIfResult(response -> Objects.equals(response.getCode(), 500))
                .withWaitStrategy(WaitStrategies.exponentialWait(2, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .withRetryListener(new RetryListener(){
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        System.out.println("RetryListener:第"+attempt.getAttemptNumber()+"次调用");
                    }
                })
                .build();
        try{
            return retryer.call(() -> rpcClient.sendRequest(rpcRequest));
        }catch (Exception e){
            e.printStackTrace();
        }
        return RpcResponse.fail();

    }
}
